package com.zhongshengnetwork.rightbe.login;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
//import android.support.v4.view.GestureDetectorCompat;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import androidx.core.view.GestureDetectorCompat;

import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.MD5;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.loading.KyLoadingBuilder;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.my.activity.MyInfoActivity;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class ForgetPasswrodActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener{
    private GestureDetectorCompat mDetector;
    private boolean flag=false;//标记edittext不会死循环
    private TopBarView topbar;
    private EditText accountText;
    private EditText codeText;
    private Button codeBt;
    private EditText firstPasswordText;
    private EditText secondPasswordText;
    private Button finishBt;
    private Timer mTimer = null;
    private TimerTask mTimerTask = null;
    private Handler mHandler = null;
    private final static int TimeOut = 91;
    private int timeCount = 0;
    private static int delay = 1000;  //1s
    private static int period = 1000;  //1s
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_passwrod);
        mDetector = new GestureDetectorCompat(this, new MyGestureListener());
        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);
        accountText = (EditText) findViewById(R.id.forget_account);
        codeText = (EditText) findViewById(R.id.forget_codetext);
        codeBt = (Button) findViewById(R.id.forget_codebt);
        firstPasswordText = (EditText) findViewById(R.id.forget_firstpassword);
        secondPasswordText = (EditText) findViewById(R.id.forget_secondpassword);
        finishBt = (Button) findViewById(R.id.forget_finishbt);

        LinearLayout forget_password = (LinearLayout) findViewById(R.id.forget_password);
        forget_password.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());

        accountText.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        accountText.setHintTextColor(AppThemeUtils.getInstance().getLightTextColor());
        accountText.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());

        codeText.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        codeText.setHintTextColor(AppThemeUtils.getInstance().getLightTextColor());
        codeText.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());

        firstPasswordText.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        firstPasswordText.setHintTextColor(AppThemeUtils.getInstance().getLightTextColor());
        firstPasswordText.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());

        secondPasswordText.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        secondPasswordText.setHintTextColor(AppThemeUtils.getInstance().getLightTextColor());
        secondPasswordText.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());

        codeBt.setBackgroundResource(AppThemeUtils.getInstance().getComsytleBg());
        finishBt.setBackgroundResource(AppThemeUtils.getInstance().getComsytleBg());

        // 定义Handler
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg == null){
                    return;
                }
                //handler处理消息
                if(msg.what>0){
                    codeBt.setText(msg.what+"秒");
                }else{
                    //在handler里可以更改UI组件
                    stopTimer();
                    codeBt.setText("获取验证码");
                }
            }
        };




    }

    private void startTimer(){
        if (mTimer == null) {
            mTimer = new Timer();
        }

        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    if (timeCount > 0){
                        timeCount--;
                    }
                    sendMessage(timeCount);
                }
            };
        }

        if(mTimer != null && mTimerTask != null ){
            if (timeCount == 0){
                timeCount = TimeOut;
                mTimer.schedule(mTimerTask, delay, period);
            }
        }

    }

    private void stopTimer(){
        if (mTimer != null) {
            timeCount = 0;
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
        codeBt.setClickable(true);
        timeCount = 0;
    }

    public void sendMessage(int id){
        if (mHandler != null) {
            Message message = Message.obtain(mHandler, id);
            mHandler.sendMessage(message);
        }
    }

    public void hintKeyBoard() {
        //拿到InputMethodManager
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //如果window上view获取焦点 && view不为空
        if (imm.isActive() && getCurrentFocus() != null) {
            //拿到view的token 不为空
            if (getCurrentFocus().getWindowToken() != null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    //获取验证码
    private void getCode(){
        if (accountText.getText().toString().trim().length() < 11){
            ToastUtil.show(ForgetPasswrodActivity.this,"请输入11位手机号");
            return;
        }
        if (timeCount > 0){
            return;
        }
        codeBt.setClickable(false);
        codeBt.setText("获取中...");
        final Map<String,String> map = new HashMap<String, String>();
        map.put(APIKey.accountKey, accountText.getText().toString());
        map.put(APIKey.typeKey, Constant.passwordCode+"");
        HttpsUtils.getCodeDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    startTimer();
                }else {
                    ToastUtil.show(ForgetPasswrodActivity.this,commonModel.getMsg());
                    stopTimer();
                    codeBt.setText("获取验证码");
                    codeBt.setClickable(true);
                    return;
                }
            }

            @Override
            public void onError(String msg) {
                stopTimer();
                codeBt.setText("获取验证码");
                codeBt.setClickable(true);
            }
        });
    }

    //修改密码
    private void changePassword(){
        finishBt.setClickable(false);
        KyLoadingBuilder dialog = new KyLoadingBuilder(ForgetPasswrodActivity.this);
        dialog.setIcon(R.drawable.loading04);
        dialog.setText("正在提交...");
        dialog.setOutsideTouchable(false);//点击空白区域是否关闭
        dialog.setBackTouchable(true);//按返回键是否关闭
        dialog.show();
        final Map<String,String> map = new HashMap<String, String>();
        map.put(APIKey.accountKey,accountText.getText().toString());
        map.put(APIKey.passwordKey, MD5.GetMD5Code(firstPasswordText.getText().toString()));
        map.put(APIKey.randcodeKey,codeText.getText().toString());
        HttpsUtils.changePasswordDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                dialog.dismiss();
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    ToastUtil.show(ForgetPasswrodActivity.this,"修改密码成功");
                    finish();
                }else {
                    finishBt.setClickable(true);
                    ToastUtil.show(ForgetPasswrodActivity.this,commonModel.getMsg());
                }
            }

            @Override
            public void onError(String msg) {
                dialog.dismiss();
                finishBt.setClickable(true);
                ToastUtil.show(ForgetPasswrodActivity.this,"提交失败");
            }
        });
    }

    /**
     * @param v
     */
    public void onClickCode(View v) {
        hintKeyBoard();
        getCode();
    }

    public void onClickFinish(View v) {
        hintKeyBoard();
        if (accountText.getText().toString().trim().length() < 11){
            ToastUtil.show(ForgetPasswrodActivity.this,"请输入11位手机号");
            return;
        }
        if (codeText.getText().toString().trim().length() < 6){
            ToastUtil.show(ForgetPasswrodActivity.this,"请输入6位验证码");
            return;
        }

        if (firstPasswordText.getText().toString().trim().length() < 6){
            ToastUtil.show(ForgetPasswrodActivity.this,"请输入6~20位数字或字母密码");
            return;
        }
        if (secondPasswordText.getText().toString().trim().length() < 6){
            ToastUtil.show(ForgetPasswrodActivity.this,"请确认输入6~20位数字或字母密码");
            return;
        }

        if (!firstPasswordText.getText().toString().equals(secondPasswordText.getText().toString())){
            firstPasswordText.setText("");
            secondPasswordText.setText("");
            ToastUtil.show(ForgetPasswrodActivity.this,"两次输入的密码不一致，请重新输入");
            return;
        }
        stopTimer();
        changePassword();
    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        hintKeyBoard();
        //Toast.makeText(LoginActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();
        stopTimer();
        finish();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    /**
     * 屏幕事件
     * @param event
     * @return
     */
    @Override
    public boolean onTouchEvent(MotionEvent event){
        this.mDetector.onTouchEvent(event);
        return super.onTouchEvent(event);
    }

    class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
        /**
         * 屏幕操作事件
         */
        private static final String DEBUG_TAG = "Gestures";
        @Override
        public boolean onDown(MotionEvent event) {
            Log.d(DEBUG_TAG,"onDown: " + event.toString());
            /*
            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            boolean isOpen=imm.isActive();//isOpen若返回true，则表示输入法打开
            if(isOpen == true){
                //隐藏键盘
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
            */
            hintKeyBoard();
            return true;
        }

        @Override
        public boolean onFling(MotionEvent event1, MotionEvent event2,
                               float velocityX, float velocityY) {
            Log.d(DEBUG_TAG, "onFling: " + event1.toString()+event2.toString());
            return true;
        }
    }
}
